import { messages } from "share/common";
import React, { Component, PropTypes } from 'react';
import { Form, Icon, Dropdown, Menu, Modal, Row, Col, Input, message, Spin, Tooltip } from 'antd'
import AdvancedSearchFormItem from 'components/advanced-search/advanced-search-form-item'
import advancedSearchService from './advanced-search.service'
import 'styles/components/advanced-search/advanced-search-title.scss'
import { stringifyJSONValue, parseJSONValue } from './utils'

class AdvancedSearchTitle extends Component {

  state = {
    current: null,
    conditionList: [],
    modalVisible: false,
    nowEdit: {},
    loading: false,
    saving: false,
    getting: false,
    operatingId: null
  };

  componentDidMount() {
    const { tableName, onSearchParent, searchForm } = this.props;
    if(tableName && searchForm.length > 0) {
      this.getConditionList(true);
    } else {
      onSearchParent();
    }
  }

  getConditionList = firstMount => {
    const { tableName, onChangeCondition, searchForm, onSearchParent } = this.props;
    this.setState({ loading: true });
    advancedSearchService.getConditionList(tableName)
      .then(res => {
        let defaultCondition = res.data.find(item => item.default);
        this.setState({ conditionList: res.data });
        if(firstMount) {
          if(defaultCondition) {
            let gettingMessage = message.loading(messages('components.key1050')/*查询中*/, 0);
            advancedSearchService.getConditionById(defaultCondition.id)
              .then(innerRes => {
                let values = parseJSONValue(innerRes.data.queryValueDTOList, searchForm);
                this.setState({ current: innerRes.data });
                onChangeCondition(values);
              })
              .finally(() => {
                gettingMessage();
              });
          } else {
            onSearchParent();
          }
        }
      })
      .catch(() => {
        if(firstMount)
          onSearchParent();
      })
      .finally(() => {
        this.setState({ loading: false });
      })
  };

  onClickMenu = ({ key }) => {
    const { onChangeCondition, form, parentForm, tableName, searchForm } = this.props;
    if(key === 'new') {
      this.setState({
        nowEdit: {
          tableName,
          queryName: '',
          queryValueDTOList: [],
          default: false
        },
        modalVisible: true
      } , () => {
        form.setFieldsValue(parentForm.getFieldsValue());
      });
    } else if(key === 'default') {
      parentForm.resetFields();
      this.setState({ current: null });
      onChangeCondition(parentForm.getFieldsValue());
    } else {
      let gettingMessage = message.loading(messages('components.key1050')/*查询中*/, 0);
      advancedSearchService.getConditionById(key)
        .then(res => {
          let values = parseJSONValue(res.data.queryValueDTOList, searchForm);
          this.setState({ current: res.data });
          onChangeCondition(values);
          gettingMessage();
        })
        .finally(() => {
          gettingMessage();
        })
    }
  };

  onOkModal = () => {
    const { form, onChangeCondition, searchForm } = this.props;
    const { nowEdit } = this.state;
    if(!nowEdit.queryName)
      message.error(messages('components.key1026')/*请输入条件名称*/);
    else {
      form.validateFields((error, values) => {
        if(!error) {
          nowEdit.queryValueDTOList = stringifyJSONValue(values, searchForm, nowEdit.queryValueDTOList);
          this.setState({ saving: true });
          advancedSearchService.setCondition(nowEdit)
            .then(res => {
              message.success(messages('components.key1020')/*条件保存成功*/);
              this.setState({ nowEdit, modalVisible: false, current: res.data }, () => {
                onChangeCondition(values);
                this.getConditionList();
              })
            })
            .finally(() => {
              this.setState({ saving: false });
            })
        }
      });
    }
  };

  renderModal = () => {
    const { searchForm, form } = this.props;
    const { modalVisible, nowEdit, saving, getting } = this.state;
    return <Modal
      width={550}
      wrapClassName='advanced-search-title-condition-modal'
      visible={modalVisible}
      title={messages('components.key1027')/*常用条件*/}
      onCancel={this.toState({ nowEdit: {}, modalVisible: false })}
      onOk={this.onOkModal}
      confirmLoading={saving}
      maskClosable={false}
    >
      <Spin spinning={getting}>
        <Row gutter={20} style={{ paddingLeft: 15 }}>
          <Col span={12}>
            <Form.Item
              label={messages('components.key1028')/*条件名称*/}
              required
            >
              <Input
                maxLength={50}
                placeholder={messages('components.key1026')/*请输入条件名称*/}
                value={nowEdit.queryName}
                onChange={e => this.setState({ nowEdit: { ...nowEdit, queryName: e.target.value } })}
              />
            </Form.Item>
          </Col>
        </Row>
        <Form className='advanced-search-title-condition-modal-form'>
          <Row gutter={20}>
            {searchForm.map(field => (
              <Col span={field.row ? 24 : 12}>
                <AdvancedSearchFormItem
                  form={form}
                  field={field}
                />
              </Col>
            ))}
          </Row>
        </Form>
      </Spin>
    </Modal>
  };

  onEditCondition = (e, condition) => {
    e.stopPropagation();
    this.setState({ getting: true, modalVisible: true });
    advancedSearchService.getConditionById(condition.id)
      .then(res => {
        const { form, searchForm } = this.props;
        let values = parseJSONValue(res.data.queryValueDTOList, searchForm);
        form.setFieldsValue(values);
        this.setState({ nowEdit: res.data });
      })
      .finally(() => {
        this.setState({ getting: false })
      });
  };

  onDefaultCondition = (e, condition, target) => {
    e.stopPropagation();
    this.setState({ operatingId: condition.id });
    advancedSearchService.setCondition({ ...condition, default: target })
      .then(() => {
        message.success(messages('components.key1029')/*设置成功*/);
        const { conditionList } = this.state;
        this.setState({
          conditionList: conditionList.map(item => {
            if(item.id === condition.id)
              item.default = target;
            return item;
          })
        })
      })
      .finally(() => {
        this.setState({ operatingId: null });
      });
  };

  onDeleteCondition = (e, condition) => {
    e.stopPropagation();
    e.stopPropagation();
    Modal.confirm({
      title: messages('components.key1030',{arg1: condition.queryName})/*你确定要删除条件 {arg1} 吗?*/,
      onOk: () => {
        this.setState({ operatingId: condition.id });
        return advancedSearchService.setCondition({ ...condition, deleted: true })
          .then(() => {
            message.success(messages('common.delete.successful')/*删除成功*/);
            const { conditionList } = this.state;
            this.setState({
              conditionList: conditionList.map(item => {
                item.id === condition.id && (item.deleted = true);
                return item;
              })
            })
          })
          .finally(() => {
            this.setState({ operatingId: null });
          });
      },
      onCancel() { },
    });
  };

  render() {
    const { title, searchForm, tableName } = this.props;
    const { conditionList, current, operatingId } = this.state;
    let showConditionList = tableName && searchForm.length > 0;
    const renderTitle = searchForm.length > 0 ? <span>
      {current ? current.queryName : title}
      {showConditionList && <Icon type="down" style={{ marginLeft: 5 }}/>}
    </span> : '';
    const menu = (
      <Menu onClick={this.onClickMenu} className='advanced-search-title-menu'>
        <Menu.Item key="default">{messages('components.key1031')/*初始*/}</Menu.Item>
        <Menu.Divider />
        {conditionList
          .filter(condition => !condition.deleted)
          .map(condition => <Menu.Item key={condition.id}>
          <div className={this.classNames([
            'advanced-search-title-menu-item',
            { 'advanced-search-title-menu-item-selected': current && current.id && current.id === condition.id }
            ])}
          >
            <Tooltip title={<span>{condition.queryName}</span>} placement='topLeft'>
              {condition.queryName}
            </Tooltip>
            <span className='advanced-search-title-menu-item-operate'>
              {operatingId === condition.id ? (
                <Icon type='loading' />
              ) : (
                <span>
                  <Tooltip title={<span>{messages('common.edit')/*编辑*/}</span>}>
                     <Icon type="edit" className='edit-icon' onClick={e => this.onEditCondition(e, condition)}/>
                  </Tooltip>
                  <Tooltip title={<span>{messages('common.delete')/*删除*/}</span>}>
                    <Icon type="delete" className='delete-icon' onClick={e => this.onDeleteCondition(e, condition)}/>
                  </Tooltip>
                  <Tooltip title={<span>{condition.default ? messages('components.key1059')/*取消默认*/ : messages('components.key805')/*设为默认*/}</span>}>
                    <Icon
                      type={condition.default ? 'star' : 'star-o'}
                      className='default-icon'
                      onClick={e => this.onDefaultCondition(e, condition, !condition.default)}
                    />
                  </Tooltip>
                </span>
              )}
            </span>
          </div>
        </Menu.Item>)}
        <Menu.Divider />
        <Menu.Item key="new"><Icon type="plus" />&nbsp;{messages('components.key1032')/*新建常用条件*/}</Menu.Item>
      </Menu>
    );
    return <span className='advanced-search-title'>
      {!showConditionList ? renderTitle : (
        <Dropdown
          overlay={menu}
          trigger={['click']}
          getPopupContainer={triggerNode => triggerNode.parentNode}
          className='advanced-search-title-trigger'
        >
          <span>
            {renderTitle}
            {this.renderModal()}
          </span>
        </Dropdown>
      )}
    </span>
  }

  static propTypes = {
    title: PropTypes.any,
    onChangeCondition: PropTypes.func,
    tableName: PropTypes.string,
    onSearchParent: PropTypes.func
  };

  static defaultProps = {
    onChangeCondition: () => {},
    onSearchParent: () => {}
  }
}

export default Form.create()(AdvancedSearchTitle);
